home *** CD-ROM | disk | FTP | other *** search
/ QRZ! Ham Radio 8 / QRZ Ham Radio Callsign Database - Volume 8.iso / mac / files / t_sys5 / unixcpio.gz / unixnet.cpio / daemon.c < prev    next >
C/C++ Source or Header  |  1994-07-11  |  886b  |  54 lines

  1. /*    Detach a daemon process from login session context */
  2.  
  3. #include <signal.h>
  4. #include <stdio.h>
  5. #if    (defined(SUNOS4) || defined(BSD))
  6. #include <sys/param.h>
  7. #define    _NFILE NOFILE
  8. #endif
  9.  
  10. #ifdef    SYSV
  11. extern void exit();
  12. #else
  13. extern int exit();
  14. #endif
  15.  
  16. void
  17. daemon()
  18. {
  19.     int fd;
  20.  
  21.     /* if started by init there's no need to detach */
  22.  
  23.     if (getppid() == 1)
  24.         goto out;
  25.  
  26.     /* ensure process is not a process group leader */
  27.  
  28.     if (fork() != 0)
  29.         exit(0);    /* parent */
  30.  
  31.     /* child */
  32.  
  33.     (void)setpgrp();        /* lose ctrl term, chg proc grp */
  34.  
  35.     (void)signal(SIGHUP, SIG_IGN);    /* immune from pgrp death */
  36.  
  37.     if (fork() != 0)    /* become non pgrp leader */
  38.         exit(0);    /* first child */
  39.  
  40.     /* close all file descriptors */
  41.  
  42. out:
  43.     for (fd = 0; fd < _NFILE; fd++) {
  44.         (void)fclose(&_iob[fd]);
  45.         (void)close(fd);
  46.     }
  47.  
  48. /*    (void)chdir("/");        /* move off any mounted file system */
  49.  
  50.     (void)umask(0);
  51.  
  52.     return;
  53. }
  54.